package com.mxw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mxw.entity.Resource;
import com.mxw.entity.UserResourceCollection;
import com.mxw.mapper.ResourceMapper;
import com.mxw.mapper.UserResourceCollectionMapper;
import com.mxw.model.PageRequest;
import com.mxw.model.PageResult;
import com.mxw.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private UserResourceCollectionMapper collectionMapper;

    @Override
    public PageResult<Resource> getResourcePage(PageRequest request) {
        // 创建分页对象
        Page<Resource> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        // 创建条件构造器
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        
        // 添加搜索条件
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.like(Resource::getTitle, request.getKeyword());
        }
        
        // 添加排序条件
        wrapper.orderByDesc(Resource::getCreateTime);
        
        // 执行分页查询
        IPage<Resource> resourcePage = resourceMapper.selectPage(page, wrapper);
        
        // 转换为自定义分页结果
        return PageResult.of(
            resourcePage.getRecords(),
            resourcePage.getTotal(),
            request.getPageNum(),
            request.getPageSize()
        );
    }

    @Override
    public Resource getResourceById(Integer id) {
        if (id == null) {
            return null;
        }
        // 获取资源详情
        Resource resource = resourceMapper.selectById(id);
        if (resource != null) {
            // 增加浏览次数
            resource.setViewCount(resource.getViewCount() == null ? 1L : resource.getViewCount() + 1);
            resourceMapper.updateById(resource);
        }
        return resource;
    }

    @Override
    public PageResult<Resource> getRelatedResources(Integer currentResourceId, PageRequest request) {
        if (currentResourceId == null) {
            return PageResult.of(Collections.emptyList(), 0L, request.getPageNum(), request.getPageSize());
        }

        // 获取当前资源
        Resource currentResource = resourceMapper.selectById(currentResourceId);
        if (currentResource == null) {
            return PageResult.of(Collections.emptyList(), 0L, request.getPageNum(), request.getPageSize());
        }

        // 创建分页对象
        Page<Resource> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        // 创建条件构造器
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        
        // 排除当前资源
        wrapper.ne(Resource::getId, currentResourceId);
        
        // 根据标题或内容相似度查询相关资源
        if (StringUtils.hasText(currentResource.getTitle())) {
            wrapper.like(Resource::getTitle, currentResource.getTitle())
                  .or()
                  .like(Resource::getContent, currentResource.getTitle());
        }
        
        // 添加排序条件
        wrapper.orderByDesc(Resource::getCreateTime);
        
        // 执行分页查询
        IPage<Resource> resourcePage = resourceMapper.selectPage(page, wrapper);
        
        return PageResult.of(
            resourcePage.getRecords(),
            resourcePage.getTotal(),
            request.getPageNum(),
            request.getPageSize()
        );
    }

    @Override
    public boolean isResourceCollected(Integer resourceId, Integer userId) {
        if (resourceId == null || userId == null) {
            return false;
        }
        
        // 创建条件构造器
        LambdaQueryWrapper<UserResourceCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserResourceCollection::getResourceId, resourceId)
               .eq(UserResourceCollection::getUserId, userId);
        
        // 查询是否存在收藏记录
        return collectionMapper.selectCount(wrapper) > 0;
    }

    @Override
    @Transactional
    public void collectResource(Integer resourceId, Integer userId) {
        if (resourceId == null || userId == null) {
            return;
        }

        // 检查是否已经收藏
        if (isResourceCollected(resourceId, userId)) {
            return;
        }

        // 创建收藏记录
        UserResourceCollection collection = new UserResourceCollection();
        collection.setResourceId(resourceId);
        collection.setUserId(userId);
        collection.setCreateTime(LocalDateTime.now());
        collection.setModifyTime(LocalDateTime.now());

        // 保存收藏记录
        collectionMapper.insert(collection);
    }

    @Override
    @Transactional
    public void uncollectResource(Integer resourceId, Integer userId) {
        if (resourceId == null || userId == null) {
            return;
        }

        // 创建条件构造器
        LambdaQueryWrapper<UserResourceCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserResourceCollection::getResourceId, resourceId)
               .eq(UserResourceCollection::getUserId, userId);

        // 删除收藏记录
        collectionMapper.delete(wrapper);
    }

    @Override
    public Resource getResourceByTitle(String title) {
        if (!StringUtils.hasText(title)) {
            return null;
        }
        
        // 创建条件构造器
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getTitle, title);
        
        // 获取资源详情
        Resource resource = resourceMapper.selectOne(wrapper);
        if (resource != null) {
            // 增加浏览次数
            resource.setViewCount(resource.getViewCount() == null ? 1L : resource.getViewCount() + 1);
            resourceMapper.updateById(resource);
        }
        return resource;
    }

    @Override
    public PageResult<Resource> getUserCollections(Integer userId, PageRequest request) {
        if (userId == null) {
            return PageResult.of(Collections.emptyList(), 0L, request.getPageNum(), request.getPageSize());
        }

        // 创建分页对象
        Page<Resource> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        // 创建条件构造器
        LambdaQueryWrapper<UserResourceCollection> collectionWrapper = new LambdaQueryWrapper<>();
        collectionWrapper.eq(UserResourceCollection::getUserId, userId)
                        .orderByDesc(UserResourceCollection::getCreateTime);
        
        // 获取用户的收藏记录
        List<UserResourceCollection> collections = collectionMapper.selectList(collectionWrapper);
        
        if (collections.isEmpty()) {
            return PageResult.of(Collections.emptyList(), 0L, request.getPageNum(), request.getPageSize());
        }
        
        // 获取收藏的资源ID列表
        List<Integer> resourceIds = collections.stream()
                .map(UserResourceCollection::getResourceId)
                .collect(Collectors.toList());
        
        // 查询资源详情
        LambdaQueryWrapper<Resource> resourceWrapper = new LambdaQueryWrapper<>();
        resourceWrapper.in(Resource::getId, resourceIds)
                      .orderByDesc(Resource::getCreateTime);
        
        // 执行分页查询
        IPage<Resource> resourcePage = resourceMapper.selectPage(page, resourceWrapper);
        
        return PageResult.of(
            resourcePage.getRecords(),
            resourcePage.getTotal(),
            request.getPageNum(),
            request.getPageSize()
        );
    }
} 